//
//  EntrepreneurDetailMessageController.m
//  BigToBig
//
//  Created by yi liu on 16/7/28.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "EntrepreneurDetailMessageController.h"
#import "EntrepreneurDetailMessageView.h"
#import "SKSTableView.h"
#import "SKSTableViewCell.h"
#import "SKSTableViewCellIndicator.h"
#import "BasicInfoTableViewCell.h"
#import "ProjectDetailViewController.h"
#import "FocusProjectModel.h"
#import "CreatedProjectModel.h"
#import "FocusPartnerModel.h"

@interface EntrepreneurDetailMessageController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    SKSTableViewDelegate
>

@property (nonatomic , strong)EntrepreneurDetailMessageView *entrepreneurDetailMessageView;

@property (nonatomic , strong)SKSTableView *sksTableView;

@property (nonatomic , strong)NSArray *content;

@property (nonatomic , strong)UIButton *focusButton;
@property (nonatomic , assign)NSInteger focusProjectCount;

@property (nonatomic , strong)NSMutableArray *focusModelArr;
@property (nonatomic , strong)NSMutableArray *createdModelArr;
@property (nonatomic , strong)NSMutableArray *partnerModelArr;
@property (nonatomic , assign)NSInteger isFocused;

@end

@implementation EntrepreneurDetailMessageController

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    [self ifFocusThisGuy];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createData];
    [self focusProjectModel];
    [self createdProjectLoad];
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = self.model.name;
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    [self createView];
}

#pragma mark - Loading数据
- (void)createData{
    self.content = @[@"最高学历",@"创业理念",@"创建的项目",@"关注的项目",@"创业伙伴",@"创业导师"];

}

- (void)LoadPartnerInformation{
    self.partnerModelArr = [NSMutableArray array];
    NSDictionary *params = @{@"user_id":_model.user_id};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/partner/get_partners_by_relation_user?user_id=%@&limit=0&offset=0",_model.user_id];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *createdProjectsArr = [dict objectForKey:@"PartnerList"];
        NSLog(@"%@",createdProjectsArr);
        for (NSDictionary *dic in createdProjectsArr) {
            FocusPartnerModel *createdProjectModel = [FocusPartnerModel FocusPartnerModelWithDict:dic];
            [self.partnerModelArr addObject:createdProjectModel];
        }
        
        [self.sksTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];

}

- (void)createdProjectLoad{
    self.createdModelArr = [NSMutableArray array];
    NSDictionary *params = @{@"user_id":_model.user_id};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/project/show_projects?user_id=%@",_model.user_id];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *createdProjectsArr = [dict objectForKey:@"projects"];
        NSLog(@"%@",createdProjectsArr);
        for (NSDictionary *dic in createdProjectsArr) {
            CreatedProjectModel *createdProjectModel = [CreatedProjectModel CreatedProjectModelWithDict:dic];
            [self.createdModelArr addObject:createdProjectModel];
        }
        
        [self.sksTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];

}

- (void)ifFocusThisGuy{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follow_id = [userDefault objectForKey:@"userID"];
    NSString *follower_id = self.model.user_id;
    if (follow_id.integerValue == follower_id.integerValue) {
        
    }
    else{
        NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/show_relation?" params:params success:^(id json) {
            NSString *type = [json objectForKey:@"type"];
            self.isFocused = type.integerValue;
            // 关注按钮
            self.focusButton = [UIButton  buttonWithType:UIButtonTypeSystem];
            self.focusButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
            [self.view addSubview:self.focusButton];
            [self.focusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            if (self.isFocused) {

                [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
                self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
            }
            else{
                [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
                self.focusButton.backgroundColor = [UIColor lightGrayColor];
            }
            
            NSLog(@"%ld",self.isFocused);
            [self.focusButton addTarget:self action:@selector(focusButtonAction:) forControlEvents:UIControlEventTouchUpInside];

        } failure:^(NSError *error) {
            
            
        }];
    }
}

- (void)focusProjectModel{
    self.focusModelArr = [NSMutableArray new];
    
    NSDictionary *params = @{@"user_id":_model.user_id};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/notice_project/show_project?user_id=%@&offset=0&limit=10",_model.user_id];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSNumber *count = [dict objectForKey:@"count"];
        NSArray *noticeProjectsArr = [dict objectForKey:@"notice_projects"];
        for (NSDictionary *dic in noticeProjectsArr) {
            FocusProjectModel *focusModel = [FocusProjectModel FocusProjectModelWithDict:dic];
            [self.focusModelArr addObject:focusModel];
        }
        self.focusProjectCount = self.focusProjectCount + count.integerValue;
        [self.sksTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark 导航栏左右Button
- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [backBtn addTarget:self action:@selector(backController:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
    
}

- (void)backController:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)createView{
    // 创建头视图
    self.entrepreneurDetailMessageView = [[EntrepreneurDetailMessageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    self.entrepreneurDetailMessageView.nameLabel.text = self.model.name;
    self.entrepreneurDetailMessageView.jobLabel.text = self.model.jobTitle;
    self.entrepreneurDetailMessageView.backgroundColor = [UIColor whiteColor];
    [self.entrepreneurDetailMessageView.headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://61.135.176.43:6080/data/HeadPortrait/%@",_model.headImage]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
    self.entrepreneurDetailMessageView.groupLabel.text = @"创业者";
    if (_model.selfIntroduction != nil) {
        self.entrepreneurDetailMessageView.personalInfoLabel.text = _model.selfIntroduction;

    }
    else{
        self.entrepreneurDetailMessageView.personalInfoLabel.text = @"这个人很懒，自我介绍都还没有写哦~";

    }
    [self.entrepreneurDetailMessageView layoutSubviews];
    // 主tableView
    self.sksTableView = [[SKSTableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.sksTableView.tableHeaderView = self.entrepreneurDetailMessageView;
    [self.view addSubview:_sksTableView];
    self.sksTableView.delegate = self;
    self.sksTableView.dataSource = self;
    self.sksTableView.SKSTableViewDelegate = self;
    self.sksTableView.rowHeight = 80;
    [self.sksTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [self.sksTableView registerClass:[BasicInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass( [BasicInfoTableViewCell class])];
    self.sksTableView.bounces = NO;
//    self.sksTableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.sksTableView.sectionFooterHeight = 10;
  }
- (void)focusButtonAction:(UIButton *)button{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follower_id = [userDefault objectForKey:@"userID"];
    NSString *follow_id = self.model.user_id;
    NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
    if (self.isFocused == 1) {
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/add_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = [UIColor lightGrayColor];
            self.isFocused = 0;
            
        } failure:^(NSError *error) {
            
            
        }];
    }
    else{

        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/cancel_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
            self.isFocused = 1;
            
        } failure:^(NSError *error) {
            
            
        }];
    }

}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 0;
    }
    if (indexPath.section == 1) {
        return 0;
    }
    if (indexPath.section == 2) {
        return _createdModelArr.count;
    }
    if (indexPath.section == 3) {
        return _focusProjectCount;
    }
    if (indexPath.section == 4) {
        return _partnerModelArr.count;
    }
    if (indexPath.section == 5) {
        return 3;
    }
    else{
        return 0;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 6;
//    if (tableView == self.sksTableView) {
//        return self.contents.count;
//    }
//    else{
//        return 3;
//    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"SKSTableViewCell";
    
    SKSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell)
        cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    cell.textLabel.text = self.content[indexPath.section];

    if (indexPath.section == 0 || indexPath.section == 1) {
        cell.isExpandable = NO;
    }
    else{
        if (_focusProjectCount == 0 && indexPath.section == 3) {
            cell.isExpandable = NO;
        }
        else if (_createdModelArr.count == 0 &&indexPath.section == 2) {
            cell.isExpandable = NO;
        }
        else if (_partnerModelArr.count == 0 &&indexPath.section == 4){
            cell.isExpandable = NO;
        }
        else{
            cell.isExpandable = YES;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"BasicInfoTableViewCell";
    
    BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    if (!cell)
        cell = [[BasicInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    if (indexPath.section == 3) {
        if (self.focusProjectCount > 0) {
            FocusProjectModel *focusModel = self.focusModelArr[indexPath.subRow - 1];
            [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",focusModel.project_logo]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
            cell.nameLabel.text = focusModel.project_name;
            cell.describe.text = focusModel.project_brief_introduction;
            
        }
    }
    if (indexPath.section == 2) {
        if (_createdModelArr.count > 0) {
            CreatedProjectModel *createdModel = self.createdModelArr[indexPath.subRow - 1];
            [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",createdModel.project_logo]]];
            cell.nameLabel.text = createdModel.project_name;
            cell.describe.text = createdModel.brief_introduction;

        }
    }
    if (indexPath.section == 4) {
        if (_partnerModelArr.count > 0) {
            FocusPartnerModel *partnerModel = self.partnerModelArr[indexPath.subRow - 1];
            [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",partnerModel.headImage]]];
            cell.nameLabel.text = partnerModel.name;
            cell.describe.text = partnerModel.selfIntroduction;

        }

    }

    tableView.rowHeight = 80;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 2 ||indexPath.section == 3){
        if (indexPath.row > 0) {
            ProjectDetailViewController *detailVC = [[ProjectDetailViewController alloc]init];
            if(indexPath.section == 3){
                FocusProjectModel *focusModel = self.focusModelArr[indexPath.row - 1];
                detailVC.project_id = focusModel.project_id;
            }
            else{
                CreatedProjectModel *createdModel = self.createdModelArr[indexPath.row - 1];
                detailVC.project_id = createdModel.project_id;
            }
            [self.navigationController pushViewController:detailVC animated:YES];
            [detailVC hidesBottomBarWhenPushed];
        }

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
